package mod.luckymod.event;

import mod.luckymod.effects.TetanusEffect;
import mod.luckymod.items.SodiumEquipment;
import mod.luckymod.items.SodiumSword;
import net.minecraft.core.BlockPos;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.DamageTypeTags;
import net.minecraft.tags.FluidTags;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.SwordItem;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.AABB;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.List;
import java.util.Random;

import static com.simibubi.create.AllTags.forgeItemTag;

@Mod.EventBusSubscriber(modid = "luckymod")
public class EventHandler {
    private static final double DETECTION_RADIUS = 8.0; // 检测玩家周围8格范围内的钠物品
    private static final int DAMAGE_INTERVAL_TICKS = 20; // 20 ticks = 1秒
    private static int tickCounter = 0;

    @SubscribeEvent
    public static void onPlayerTick(TickEvent.PlayerTickEvent event) {
        // 只在特定阶段（通常为END）和服务端执行逻辑
        if (event.phase != TickEvent.Phase.END || event.player.level().isClientSide) return;

        Player player = event.player;

        tickCounter++;
        if (tickCounter >= DAMAGE_INTERVAL_TICKS) {
            tickCounter = 0; // 重置计数器

            // 检查玩家是否在水中且穿着了任意一件自定义盔甲
            if (player.isInWater() && isWearingAnyCustomArmor(player)) {
                // 造成半颗心（1点）伤害，伤害来源设为溺水
                player.hurt(player.damageSources().inFire(), 1.0f);
            }
        }
    }

    private static boolean isWearingAnyCustomArmor(Player player) {
        // 检查玩家是否至少穿戴了一件你的自定义盔甲
        Iterable<ItemStack> armorSlots = player.getArmorSlots();
        for (ItemStack stack : armorSlots) {
            if (stack.getItem()instanceof SodiumEquipment) { // 替换为你的盔甲物品类
                return true;
            }
        }
        return false;
    }
    @SubscribeEvent
    public static void onWorldTick(TickEvent.LevelTickEvent event) {
        if (event.phase != TickEvent.Phase.END || event.level.isClientSide()) return;
        Level level = event.level;
        // 遍历所有玩家，以每个玩家为中心进行检测
        level.players().forEach(player -> {
            // 1. 创建精确的边界框：以玩家为中心，边长为检测半径*2的立方体
            AABB detectionArea = new AABB(
                    player.getX() - DETECTION_RADIUS,
                    player.getY() - DETECTION_RADIUS,
                    player.getZ() - DETECTION_RADIUS,
                    player.getX() + DETECTION_RADIUS,
                    player.getY() + DETECTION_RADIUS,
                    player.getZ() + DETECTION_RADIUS
            );

            // 2. 高效查询：直接获取边界框内，且具有“钠”标签的**物品实体**
            // 这避免了遍历所有实体，性能大幅提升！
            List<ItemEntity> sodiumItems = level.getEntitiesOfClass(
                    ItemEntity.class,
                    detectionArea,
                    itemEntity -> itemEntity.getItem().is(forgeItemTag("metal/sodium")) // 谓词条件：拥有钠标签
            );

            for (ItemEntity sodiumItem : sodiumItems) {
                // 确保实体未被移除，并且精确检测是否在水中
                if (!sodiumItem.isRemoved() && isInWaterOrFlowingWater(sodiumItem)) {
                    // 创建水下爆炸
                    Explosion explosion = level.explode(
                            null,
                            sodiumItem.getX(),
                            sodiumItem.getY(),
                            sodiumItem.getZ(),
                            3.0F,
                            Level.ExplosionInteraction.BLOCK
                    );
                    explosion.explode();
                    level.playSound(null,
                            sodiumItem.getX(), sodiumItem.getY(), sodiumItem.getZ(),
                            SoundEvents.GENERIC_EXPLODE, SoundSource.BLOCKS,
                            0.5F, 0.8F + level.random.nextFloat() * 0.2F
                    );
                    // 立即移除物品实体
                    sodiumItem.kill();
                }
            }
        });
    }
    private static boolean isInWaterOrFlowingWater(ItemEntity itemEntity) {
        Level level = itemEntity.level();
        BlockPos pos = itemEntity.blockPosition();

        // 获取当前位置流体状态
        FluidState fluidState = level.getFluidState(pos);

        // 检查是否是水或流动水
        boolean isInWater = fluidState.is(Fluids.WATER) ||
                fluidState.is(Fluids.FLOWING_WATER) ||
                fluidState.getType().is(FluidTags.WATER);

        // 额外检查：确保物品实体确实在水中（碰撞检测）
        boolean isActuallySubmerged = itemEntity.isInWater() || itemEntity.isUnderWater();

        return isInWater && isActuallySubmerged;
    }
    @SubscribeEvent
    public static void onHurt(LivingHurtEvent event) {
        // 1. 检查受伤实体是否是玩家
        if(event.getEntity() instanceof Player player) {

            // 2. 检查伤害来源是否为爆炸
            if (event.getSource().is(DamageTypeTags.IS_EXPLOSION)) { // 或 event.getSource().isExplosion()
                // 3. 检查玩家是否穿戴了全套自定义盔甲
                if (isWearingFullCustomArmorSet(player)) {
                    event.setCanceled(true); // 取消此次伤害
                    // 或者 event.setAmount(0.0f); 将伤害量设置为0
                }
            }
        }else if (event.getSource().getDirectEntity() instanceof Player player) {
            ItemStack heldItem = player.getMainHandItem();

            // 确保玩家手持的是剑
            if (heldItem.getItem() instanceof SwordItem) {
                applyTetanusEffect(event.getEntity(), heldItem);
            }
        }
    }
    private static void applyTetanusEffect(LivingEntity target, ItemStack weapon) {
        Item item = weapon.getItem();
        int effectLevel = 0;
        double chance = 0.0;

        // 根据剑的类型确定几率和效果等级
        if (item == Items.WOODEN_SWORD) {
            chance = 0.10; // 10%
            // 1级
        } else if (item == Items.STONE_SWORD) {
            chance = 0.15; // 15%
            // 1级
        } else if (item == Items.IRON_SWORD) {
            chance = 0.20; // 20%
            effectLevel = 1; // 2级
        } else if (item == Items.GOLDEN_SWORD) {
            chance = 0.25; // 25%
            effectLevel = 1; // 2级
        } else if (item == Items.DIAMOND_SWORD) {
            chance = 0.28; // 28%
            effectLevel = 2; // 3级
        } else if (item == Items.NETHERITE_SWORD) {
            chance = 0.30; // 30%
            effectLevel = 2; // 3级
        }
        // 检查是否是自定义的Sodium_Sword
        else if (weapon.getItem() instanceof SodiumSword) {
            chance = 0.6; // 50%
            effectLevel = 2; // 3级
        }
        Random random = new Random();
        // 随机几率判断
        if (random.nextFloat() < chance) {
            // 应用破伤风效果，持续时间为5分钟（6000ticks）
            target.addEffect(new MobEffectInstance(
                    TetanusEffect.TETANUS.get(),
                    6000,
                    effectLevel
            ));
        }
    }
    private static boolean isWearingFullCustomArmorSet(Player player) {
        // 实现你的检查逻辑，判断玩家是否穿齐了一整套你的自定义盔甲
        // 例如，检查四个盔甲槽位的物品是否都是你的模组盔甲
        Iterable<ItemStack> armorSlots = player.getArmorSlots();
        for (ItemStack stack : armorSlots) {
            if (!(stack.getItem() instanceof SodiumEquipment)) { // 替换为你的盔甲物品类
                return false;
            }
        }
        return true;
    }
}